import toolMgr from '@/biz/base/tool.js'
import baseApi from '@/config/server/api/base.js'
import userApi from '@/config/server/api/user.js'

let orgs = []

function create(params = {}) {
  let opt = {
    key: params.key || 'orgId',
    title: params.title || '所属组织',

    tree: {
      options: orgs,
      selectPlaceholder: params.placeholder,
      saveAll: params.saveAll || false
    },
    change: params.change
  }
  toolMgr.organization(params.level || 2).then((res) => {
    orgs = res
    opt.tree.options = orgs
  })
  return opt
}

//根据城市联级
// function getAreacodePropertyList(params) {
//   return baseApi.generalConfiguration.cityList().fetch(params)
// }

let cityAttrSort = []
//获取省
function getAreacodePropertyList() {
  let params = {
    level: 2,
    page: '1',
    parentCode: '',
    rows: '100'
  }
  return baseApi.generalConfiguration
    .cityList()
    .fetch(params)
    .then((res) => {
      cityAttrSort = res.list
      cityAttrSort.map((item) => {
        item.value = item.cityCode
        item.label = item.cityName
        item.loading = false
        item.children = []
      })
      return cityAttrSort
    })
}
//根据城市联级
function getAreacodePropertyList2(params) {
  return baseApi.generalConfiguration.cityList().fetch(params)
}

function getOrg(level = 1, orgId = 1) {
  return userApi.organizationManagement.getOrgAndLevel.fetch({ level, orgId }).then((res) => {
    return res.map((itm) => {
      return {
        key: itm.orgId,
        value: itm.orgName
      }
    })
  })
}

function select(data) {
  // org1 org2 org3
  let org3 = {
    title: data.org3.title || '事业处',
    key: data.org3.key,
    rules: data.org3.rules,
    select: {
      options: [],
      clearable: true
    },
    data: data.org3.data
  }
  let org2 = {
    title: data.org2.title || '子公司',
    key: data.org2.key,
    rules: data.org2.rules,
    data: data.org2.data,
    select: {
      options: [],
      clearable: true
    },
    change: (res) => {
      res.info[data.org3.key] = null
      getOrg(3, res.value).then((res) => {
        org3.select.options = res
      })
    }
  }
  let org1 = {
    title: data.org1.title || '事业部',
    key: data.org1.key,
    rules: data.org1.rules,
    data: data.org1.data,
    select: {
      options: [],
      clearable: true
    },
    change: (res) => {
      res.info[data.org2.key] = null
      res.info[data.org3.key] = null
      getOrg(2, res.value).then((res) => {
        org2.select.options = res
      })
    }
  }
  getOrg().then((res) => {
    org1.select.options = res
  })
  return [org1, org2, org3]
}

export default {
  create,
  getAreacodePropertyList,
  getAreacodePropertyList2,
  select
}
